<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in EmloyessList"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="$emit('close')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, updateDepartments, getDepartmentsDetail } from '@/api/departments'
export default {

  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      let exisCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // this.isEdit 等于true是编辑，利用filter过滤出里面不相等id的数据，用map方法找到数据里的code
        exisCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // 用includes(value)判断用户输入的值是否和数组里的code相同，相同效验不通过，抛出错误
      if (exisCodeList.includes(value)) {
        callback(new Error(`部门编码:${value} 已存在`))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      // 通过pid找到相同的pid里的数据，在用map方法获取里面的name
      // 找到父部门里面的子部门 父部门的id是新增部门的pid
      let exisNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(exisNameList, '部门名称')
      if (this.isEdit) {
        // 通过id 用find方法找到正在编辑的数据对象
        const curDepartment = this.originList.find(item => item.id === this.id)
        console.log(curDepartment, '正在编辑的对象')
        // const pid = curDepartment.pid
        // 过滤:同一个父级，包括自己
        const brothers = this.originList.filter(item => item.pid === curDepartment.pid)
        //  通过id用filter方法筛选出不相同id的数据,在用map方法获取里面的name。
        // 过滤:同一个父级，不包括自己
        exisNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      if (exisNameList.includes(value)) {
        callback(new Error(`部门名称:${value} 已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      EmloyessList: [],
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }

        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入长度是1~300的字符', trigger: 'blur' }
        ]
      }
    }
  },
  // watch: {
  //   //  深度监听id 处理数据不更新方式
  //   'id': {
  //     deep: true,
  //     immediate: true,
  //     handler: function(newVal, oldVal) {
  //       this.lodDepartmentsDetail()
  //     }
  //   }
  // },
  created() {
    this.loadEmployeeSimple()
    this.lodDepartmentsDetail()
  },
  methods: {
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    async  lodDepartmentsDetail() {
      // isEdit 为true 是编辑获取全部数据给form，v-model双向绑定实现数据回显
      if (this.isEdit) {
        const res = await getDepartmentsDetail(this.id)
        console.log(res, '获取全部数据')
        this.form = res.data
      }
    },
    hSubmit() {
      // 兜底效验
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
        console.log(this.isEdit)
      })
    },
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        console.log(res, '修改成功')
        this.$message.success(res.message)
        this.$emit('success')
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res, '添加')
        // 重新渲染页面，关闭弹层
        this.$emit('success')
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 获取员工基本信息
    async loadEmployeeSimple() {
      try {
        const res = await getEmployeeSimple()
        console.log('员工信息', res)
        if (res.code === 10000) {
          this.EmloyessList = res.data
        }
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
